package com.zlx.mall.basic.web;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.zlx.mall.basic.common.exception.BizExtraRuntimeException;
import com.zlx.mall.basic.common.exception.IllegalBizArgumentException;
import com.zlx.mall.basic.common.exception.IllegalBizStatusException;
import com.zlx.mall.basic.util.JwtUtils;
import com.zlx.mall.basic.util.collection.CollectionUtil;
import com.zlx.mall.basic.web.model.BaseRequest;
import com.zlx.mall.basic.web.model.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.function.Function;

/**
 * taotao
 *
 * @description 基础controller类
 */
@RestController
@Slf4j
public abstract class BaseController {

    /**
     * 记录日志操作
     * @param request
     * @return
     */
    public BaseResponse bizExecute(BaseRequest request, Function<BaseRequest, BaseResponse> function) {
        Instant start = Instant.now();
        BaseResponse response = null;
        try {
            //参数转换
            List<String> tokenList = request.getHeaders().get("token");
            JsonNode payload = request.getPayload();
            String mobile = null;
            Long userId = null;
            if (!CollectionUtil.isEmpty(tokenList)) {
                JSONObject jsonObject = JwtUtils.getJSONObject(tokenList.get(0));
                mobile = jsonObject.getStr("mobile");
                userId = jsonObject.getLong("id");
            }

            log.info("请求URL:{}, id: {}, 手机号:{}, 参数:{},  ", request.getUri(), userId, mobile, payload);
            //执行业务逻辑
            response = function.apply(request);
        } catch (BizExtraRuntimeException e) {
            log.error("业务异常，需要返回extraCode", e.getCause());
            return BaseResponse.failure().extra(e.getExtraCode(), e.getExtraMessage());
        } catch (IllegalBizStatusException e) {
            log.error("非法的业务状态", e.getCause());
            BaseResponse failure = BaseResponse.failure();
            failure.setMessage(e.getMessage());
            return failure;
        } catch (IllegalBizArgumentException e) {
            log.error("参数异常", e.getCause());
            BaseResponse failure = BaseResponse.failure();
            failure.setMessage(e.getMessage());
            return failure;
        } catch (Exception e) {
            log.error("系统异常", e);
            BaseResponse failure = BaseResponse.failure();
            failure.setMessage(e.getMessage());
            return failure;
        } catch (Throwable e) {
            log.error("未知的错误", e);
            return BaseResponse.failure();
        } finally {
            long millis = Duration.between(start, Instant.now()).toMillis();
            log.info("请求RUI:{},耗时{}毫秒,响应数据{}", request.getUri(), millis, response == null ? "": response.getData());
        }
        return response;
    }
}